//UIFunctions:UI交互的所有函数都在这个文件中


var FoldDivShow=new Array(10);   //标识折叠Div是否被隐藏


function InitUIs()      //初始化UI相关元素
{
    InitUIVar();
    SetUICallFunc();
    setInterval(function(){ $("#TF_posBar").fadeOut(500).fadeIn(500); },1000);//让传递函数处的光标持续闪烁
    ui_setStep(1);
    ui_setGlobalOpacity(1);
}

function InitUIVar()//初始化UI变量
{
    for(var i=0;i<FoldDivShow.length;i++) {
        FoldDivShow[i] = false;
        $("#Fold_"+i).hide();//隐藏所有折叠Div
    }
}

function SetUICallFunc()    //设置一些回调函数，详见函数内容
{
    //点击直方图画布时设置光标的位置
    document.getElementById("HistogramCanvas").onmousedown=function(event)
    {
        ui_TF_setpos(Math.floor(event.layerX/g_HBWidth));
    }
    //鼠标在直方图画布上移动时显示悬停位置
    document.getElementById("HistogramCanvas").onmousemove=function(event)
    {
        setInner("TF_MousePos","鼠标悬停位置:"+Math.floor(event.layerX/g_HBWidth));
    }
    //点击传递函数画布时设置光标的位置
    document.getElementById("TransFuncTexCanvas").onmousedown=function(event)
    {
        ui_TF_setpos(Math.floor(event.layerX/g_HBWidth));
    }
    //鼠标在传递函数画布上移动时显示悬停位置
    document.getElementById("TransFuncTexCanvas").onmousemove=function(event)
    {
        setInner("TF_MousePos","鼠标悬停位置:"+Math.floor(event.layerX/g_HBWidth));
    }
}

var rotX = 0;                   //控制仰视俯视角度
var rotY = 0;                   //控制水平旋转角
function CreateCanvas()
{
    var newCanvas = document.createElement("canvas");//输入想要创建的类型
    newCanvas.id="VolRenderCanvas";
    newCanvas.style.position = "absolute";
    //以下为鼠标点击拖动画布的事件，其控制了视角。

    var EyeDistance = 3.0;          //眼睛距离中心距离
    var dragView = false;          //是否处在拖动画布状态
    var PreMouseX, PreMouseY;       //上一帧鼠标的位置
    newCanvas.onmousedown=function(event)        //当鼠标点击画布时触发的函数
    {
        dragView = true;
        PreMouseX = event.clientX;
        PreMouseY = event.clientY;

    };
    document.onmousemove = function(event)           //因为想让鼠标离开画布后仍旧能移动视角，因此用了document的onmousemove函数
    {
        var deltaX = event.clientX - PreMouseX;
        var deltaY = event.clientY - PreMouseY;
        PreMouseX = event.clientX;
        PreMouseY = event.clientY;
        if (dragView)
        {
            rotY -= (deltaX) * 0.005;
            rotX += (deltaY) * 0.005;

            //根据两个旋转角计算g_EysPos，g_ViewX, g_ViewY, g_ViewZ,
            FillVec3Data(g_EysPos,EyeDistance*Math.cos(rotX)*Math.sin(rotY), Math.sin(rotX)*EyeDistance,-EyeDistance*Math.cos(rotX)*Math.cos(rotY));
            FillVec3Data(g_ViewZ, -g_EysPos[0], -g_EysPos[1], -g_EysPos[2]);
            Normalize(g_ViewZ);
            var ViewUp = createVector3();
            FillVec3Data(ViewUp, 0, Math.cos(rotX), 0);//当X轴旋转超过（-90°，90°）时要进行上下翻转
            VectorCross(ViewUp, g_ViewZ, g_ViewX);
            Normalize(g_ViewX);
            VectorCross(g_ViewZ, g_ViewX, g_ViewY);
            Normalize(g_ViewY);
        }
    }
    document.onmouseup = function(event)         //因为想让鼠标离开画布后仍旧能放开拖动状态，因此用了document的onmouseup函数
    {
        dragView = false;
    }
    document.body.appendChild(newCanvas);
}

function ui_FoldIdv(index)//显示/折叠Div
{
    if(FoldDivShow[index])
    {
        $("#Fold_"+index).hide(400);//jQuery函数，按ID寻找节点并对其隐藏，时间为400毫秒
        FoldDivShow[index] = false;
    }
    else
    {
        $("#Fold_"+index).show(400);//jQuery函数，按ID寻找节点并让其出现，时间为400毫秒
        FoldDivShow[index] = true;
    }
}


function  ui_setRenderSize()//重设渲染视图尺寸
{
    var size = parseInt(document.getElementById("RenderSizeInputField").value);
    if((size>=64)&&(size<=2048))
    {
        g_RenderSize =  size;

        //删除掉旧的画布节点
        var oldCanvas = document.getElementById("VolRenderCanvas");
        oldCanvas.remove();

        //创建新的画布节点
        CreateCanvas();

        //布局管理器重新布局
        LayoutMgr.RePos();

        //创建新的GLMgr并初始化
        GLMgr = new GLManager();
        GLMgr.init();

        //重新导入体数据
        readVolumeRaw();

        //重新导入传递函数纹理
        applyToShaderTFTex();
    }
    else
        alert("视图尺寸不合法！");
}


function ui_setSampleType()
{
    g_sampleType = getFloatFromInput("SampleType");
}

function ui_setStep(type)
{
    if(type==1)
        document.getElementById("stepText").value = document.getElementById("stepSlider").value;
    else
        document.getElementById("stepSlider").value = document.getElementById("stepText").value;

    g_step = 1.0/getFloatFromInput("stepSlider")
}

function ui_setGlobalOpacity(type)
{
    if(type==1)
        document.getElementById("GlobalOpacityText").value = document.getElementById("GlobalOpacitySlider").value;
    else
        document.getElementById("GlobalOpacitySlider").value = document.getElementById("GlobalOpacityText").value;

    g_GlobalOpacity = Math.pow(2.0,getFloatFromInput("GlobalOpacitySlider")/10);
    setInner("GlobalOpacityLabel","X "+Math.floor(g_GlobalOpacity*10000)/10000);
}



function ui_ModifyHistogram()
{
    var inner = getNumFromInput("HB_inner");
    var border = getNumFromInput("HB_border");
    var blank = getNumFromInput("HB_blank");

    var ColorType = getNumFromInput("HB_ColorType");
    if(ColorType==0)
        $("#HB_ColorDiv").show(400);
    else
        $("#HB_ColorDiv").hide(400);

    var colorInner = getValueFromDoc("HB_innerColor");
    var colorBorder = getValueFromDoc("HB_borderColor");

    var HBHeight = getNumFromInput("HistogramHeightValue");

    DrawHistogram(inner,border,blank,ColorType,colorInner,colorBorder,HBHeight);
}

function ui_ModifyHistogramHeight(delta)
{
    var height = getNumFromInput("HistogramHeightValue");
    height+=delta;
    if(height<0)
        height = 0;
    setValueFromDoc("HistogramHeightValue",height);

    ui_ModifyHistogram();
}

function ui_HistogramDefaultSet()
{
    setValueFromDoc("HB_inner",6);
    setValueFromDoc("HB_border",2);
    setValueFromDoc("HB_blank",4);
    setValueFromDoc("HB_ColorType",0);
    setValueFromDoc("HB_innerColor","#00ffff");
    setValueFromDoc("HB_borderColor","#000000");
    setValueFromDoc("HistogramHeightValue",0);

    ui_ModifyHistogram();
}


var g_PresentCursorPos;     //当前光标所在位置
function ui_TF_setpos(pos)
{
    g_PresentCursorPos = pos;
    ResetCursor();
    document.getElementById("TF_CursorPos").innerHTML="当前光标位置:"+pos;


    //显示当前位置的控制点的数据
    setValueFromDoc("TF_pointOpacity",g_tf_pointOpacity[g_PresentCursorPos]);
    setValueFromDoc("TF_pointColor",g_tf_pointColor[g_PresentCursorPos]);


    //根据当前位置是否有控制点来决定背景颜色和输入控件是否可读
    if(judgeCtrlPoint(pos))
    {
        document.getElementById("TFPointDataDiv").style.backgroundColor="#C76581";
        document.getElementById("TF_IfCtrlPoint").innerHTML="控制点";
        document.getElementById("TF_pointColor").removeAttribute("disabled")
        document.getElementById("TF_pointOpacity").removeAttribute("disabled");
        document.getElementById("TF_AddDelCtrlPoint").value = "删除当前位置的控制点";
    }
    else
    {
        document.getElementById("TFPointDataDiv").style.backgroundColor="#8388C7";
        document.getElementById("TF_IfCtrlPoint").innerHTML="非控制点";
        document.getElementById("TF_pointColor").setAttribute("disabled","disabled")
        document.getElementById("TF_pointOpacity").setAttribute("disabled","disabled")
        document.getElementById("TF_AddDelCtrlPoint").value = "添加控制点到当前位置";
    }
}

function ResetCursor()
{
    document.getElementById("TF_posBar").style.left=""+g_PresentCursorPos*g_HBWidth+"px";
    document.getElementById("TF_posBar").style.width = ""+g_HBWidth+"px";
}

function ui_TF_addPoint()
{
    if(judgeCtrlPoint(g_PresentCursorPos))
        delTFCtrlPoint(g_PresentCursorPos);
    else
        addTFCtrlPoint(g_PresentCursorPos);
}

function ui_TF_ModifyOpacity()
{
    g_tf_pointOpacity[g_PresentCursorPos] = getNumFromInput("TF_pointOpacity");
    ReCalculateTFTex();
    ReDrawTFTex();
}

function ui_TF_ModifyColor()
{
    g_tf_pointColor[g_PresentCursorPos] = getValueFromDoc("TF_pointColor");
    ReCalculateTFTex();
    ReDrawTFTex();
}

function ui_ChangeRealTimeType(type)        //实时/非实时渲染单选框勾选时调用
{
    if(type==0)//如果是实时渲染
    {
        document.getElementById("RenderThisFrame").setAttribute("disabled","disabled")
        if(g_RealTimeRender==false)
        {
            g_RealTimeRender = true;
            MainLoop();
        }

    }
    else
    {
        g_RealTimeRender = false;
        document.getElementById("RenderThisFrame").removeAttribute("disabled")
    }
}

function ui_RenderThisFrame()           //单击“渲染当前帧”时调用
{
    MainLoop();
}

function ui_ModifySurfaceIncreaseValue()
{
    g_SurfaceIncreaseValue = getValueFromDoc("SurfaceIncreaseValue");
}

function ui_ModifyLightIntensity(type)
{
    g_LightIntensity[type] = getValueFromDoc("LightIntensity"+type)/100;
}

function ui_ModifyLightPos()
{
    var rotX = getValueFromDoc("LightRotX")/180*Math.PI;
    var rotY = getValueFromDoc("LightRotY")/180*Math.PI;
    FillVec3Data(g_LightPos,Math.cos(rotX)*Math.sin(rotY), Math.sin(rotX),Math.cos(rotX)*Math.cos(rotY));
    Normalize(g_LightPos);
}

function ui_ModifyContPreKtKs()
{
    g_ContPreKt=getValueFromDoc("ContPreKt")/10;
    g_ContPreKs=getValueFromDoc("ContPreKs")/10;
}

function ui_ModifyFresnel()
{
    var color = colorh2d(getValueFromDoc("FresnelColor"));
    FillVec3Data(g_FresnelColor,color[0]/255,color[1]/255,color[2]/255);
    g_FresnelValue = getFloatFromInput("FresnelValue")/100;
}

function  ui_test()         //测试用
{

}